<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataItem.deviceNumber || ''} / ${dataItem.belongDate} / ${dataItem.shiftName || ''}-详情`"
		width="1200px"
		:show-confirm-btn="false"
		:show-cancel-btn="false"
		:show-close-btn="true"
		@on-close="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
	>
		<div class="flex-end-center margin-bottom-10">
			<jk-date-picker
				v-model="searchParams.fromDate"
				type="date"
				:disabled-future-time="true"
				:clearable="false"
				placeholder="班次开始日期"
				size="small"
				class="search-bar-item-size2 margin-5-0 item-gap"
			></jk-date-picker>
			<jk-select
				v-model="searchParams.fromShiftCode"
				:option-list="searchOptionConfig.shiftList"
				size="small"
				placeholder="开始班次"
				class="search-bar-item-size1 margin-5-0 item-gap"
			></jk-select>
			<jk-date-picker
				v-model="searchParams.toDate"
				type="date"
				:disabled-future-time="true"
				:clearable="false"
				placeholder="班次结束日期"
				size="small"
				class="search-bar-item-size2 margin-5-0 item-gap"
			></jk-date-picker>
			<jk-select
				v-model="searchParams.toShiftCode"
				:option-list="searchOptionConfig.shiftList"
				size="small"
				placeholder="结束班次"
				class="search-bar-item-size1 margin-5-0 item-gap"
			></jk-select>
			<!--<jk-select v-model="searchParams.workshopId" :clearable="false" placeholder="区域" :option-list="workshopList" size="small" class="search-bar-item-size1 margin-5-0 item-gap" @change="onDateChange"></jk-select>-->
			<!-- <jk-date-picker v-model="searchParams.belongDates" type="daterange" :disabled-future-time="true" :clearable="false" placeholder="日期" size="small" class="search-bar-item-size4 item-gap"></jk-date-picker>
			<jk-select v-model="searchParams.shiftCode" :option-list="searchOptionConfig.shiftList" size="small" placeholder="班次" class="search-bar-item-size1 item-gap"></jk-select> -->
			<!-- <el-time-picker
				v-model="pickerTime"
				is-range
				value-format="HH:mm:ss"
				size="small"
				range-separator="至"
				style="width: 280px;"
				class="margin-5-0 item-gap"
				start-placeholder="班次开始时间"
				end-placeholder="班次结束时间"
			>
			</el-time-picker> -->
			<!--<jk-select v-model="searchParams.duration" placeholder="时长排序" :option-list="[{id: 'asc', name:'正序'},{id: 'desc', name:'倒序'}]" size="small" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>-->
			<jk-input
				v-model="searchParams.deviceNumber"
				class="search-bar-item-size2 item-gap"
				placeholder="机台号"
				size="small"
				clearable
				@on-enter="onSearchBtn"
			/>
			<jk-select
				v-model="searchParams.position"
				label-key-name="id"
				placeholder="面位"
				:option-list="searchOptionConfig.machineFaceList"
				size="small"
				class="search-bar-item-size1 item-gap"
			></jk-select>
			<!--<jk-input v-model="searchParams.startIngotNo" class="search-bar-item-size1 margin-5-0 item-gap" placeholder="开始锭号" size="small" clearable @blur="onIngotNumberChange($event,'startIngotNo')" />-->
			<!--<jk-input v-model="searchParams.endIngotNo" class="search-bar-item-size1 margin-5-0 item-gap" placeholder="结束锭号" size="small" clearable @blur="onIngotNumberChange($event,'endIngotNo')" />-->
			<jk-search-button @click="onSearchBtn"></jk-search-button>
		</div>
		<jk-table
			:footer-method="footerMethod"
			:show-footer="true"
			border
			:data="tableData"
			:loading="tableLoading"
			:height="400"
		>
			<vxe-column
				title="日期时间"
				align="left"
				field="belongDate"
				:width="140"
			/>
			<vxe-column
				title="班次"
				align="left"
				field="shiftName"
				:min-width="80"
			/>
			<vxe-column
				title="屏幕班次"
				align="left"
				field="screenShiftName"
				:min-width="80"
			/>
			<vxe-column
				title="机台号"
				align="left"
				field="deviceNumber"
				:min-width="80"
			/>
			<vxe-column
				title="面位"
				align="left"
				field="position"
				:min-width="80"
			/>
			<vxe-column
				title="锭号"
				align="left"
				field="ingotNo"
				:min-width="80"
			/>
			<vxe-column
				title="断头开始时间"
				align="left"
				field="startTime"
				:width="160"
			/>
			<vxe-column
				title="断头结束时间"
				align="left"
				field="endTime"
				:width="160"
			/>
			<vxe-column title="时长(分)" align="left" field="duration" :min-width="80">
				<template #header>
					<div style="display: flex">
						<span>时长(分)</span>
						<span style="cursor: pointer; display: flex; align-items: center;" @click="toggleSort('duration')">
							{{ sortOrders.duration === "asc" ? "⬆" : sortOrders.duration === "desc" ? "⬇" : "⇅" }}
						</span>
					</div>
				</template>
			</vxe-column>
		</jk-table>
		<!-- 分页组件 -->
		<footer ref="box2" class="flex-end-center margin-top-10">
			<jk-page
				:page-index="searchParams.pageNo"
				:page-sizes="searchParams.pageSizes"
				:page-size="searchParams.pageSize"
				:total="totalCount"
				@on-change="onPageChange"
			/>
		</footer>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import { iotSpinBrokenHeadPage } from '@/api/statistic/spindleReports';
    import {
        pageConfig
    } from '/src/utils/jk/jk-tool';
    import XEUtils from 'xe-utils';

    export default {
        name: 'MachineArchives',
        props: {
            searchOptionConfig: {
                type: Object,
                default() {
                    return {
                        shiftList: [],
                        machineFaceList: []
                    };
                }
            },
            isRealTime: {
                type: Boolean,
                default: false
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataItem: {
                type: Object,
                default() {
                    return {};
                }
            }
        },
        mixins: [calHeight],
        data() {
            return {
                pickerTime: [],
                totalCount: null,
                apiItem: {
                    page: iotSpinBrokenHeadPage
                },
                sortOrders: {
                    duration: null
                },
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize
                },
                showDialog: false,
                tableLoading: false,
                tableData: []
            };
        },
        methods: {
            footerMethod({ columns, data }) {
                const keys = ['ingotNo', 'duration'];
                const hasData = this.tableData.length > 0;
                const totalBrokenQty = hasData ? this.tableData[0].totalBrokenQty : '';
                const totalBrokenTime = hasData ? this.tableData[0].totalBrokenTime : '';

                return [
                    columns.map((column, columnIndex) => {
                        switch (columnIndex) {
                        case 0:
                            return '合计';
                        case 5:
                            return totalBrokenQty;
                        case 8:
                            return totalBrokenTime;
                        default:
                            return keys.includes(column.field) ? XEUtils.sum(data, column.field) : null;
                        }
                    })
                ];
            },
            toggleSort(field) {
                // 重置所有排序状态
                Object.keys(this.sortOrders).forEach((key) => {
                    if (key !== field) {
                        this.sortOrders[key] = null;
                    }
                });
                // 切换当前字段的排序状态
                const currentOrder = this.sortOrders[field];

                switch (currentOrder) {
                case null:
                    this.sortOrders[field] = 'asc';
                    this.searchParams.ascField = field;
                    this.searchParams.descField = null;
                    break;
                case 'asc':
                    this.sortOrders[field] = 'desc';
                    this.searchParams.ascField = null;
                    this.searchParams.descField = field;
                    break;
                case 'desc':
                    this.sortOrders[field] = null;
                    this.searchParams.ascField = null;
                    this.searchParams.descField = null;
                    break;
                }
                // 如果未设置排序类型，则请求更新列表
                if (!this.searchParams.sortType) {
                    this.getListRequest();
                }
            },
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                this.$set(this.sortOrders, 'duration', null);
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            getListRequest() {
                this.tableData = [];
                this.tableLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                params.realtimeBroken = this.isRealTime;
                // params.belongDates = params.belongDates.map((date, index) => {
                //     const defaultTime = index === 0 ? '00:00:00' : '23:59:59';
                //     console.log(this.pickerTime, ' ====== ');
                //     const time = this.pickerTime && this.pickerTime.length > 0 ? this.pickerTime[index] : defaultTime;
                //     return `${date} ${time}`;
                // });
                return this.apiItem['page'](params).then((res) => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                });
            }
        },
        watch: {
            // 'searchParams.shiftCode': {
            //     handler(val) {
            //         const { shiftList } = this.searchOptionConfig;
            //         const selectedShift = shiftList.find(i => i.id === val);
            //         if (selectedShift) {
            //             const { beginHour, endHour } = selectedShift;
            //             this.pickerTime = [beginHour, endHour]; // 直接赋值
            //             console.log(this.pickerTime, ' this.pickerTime');
            //         }
            //     }, immediate: true
            // },

            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    const {
                        belongDate,
                        shiftCode,
                        deviceNumber,
                        position
                    } = this.dataItem;
                    this.searchParams = {
                        ...this.searchParams,
                        fromDate: belongDate,
                        toDate: belongDate,
                        fromShiftCode: shiftCode,
                        toShiftCode: shiftCode,
                        deviceNumber,
                        position
                    };
                    this.$nextTick(() => {
                        this.getListRequest();
                    });
                }
            }
        }
    };
</script>
